<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>深入理解JavaScript之作用域闭包 - smartzheng</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="smartzheng" /><meta name="description" content="在Java中，由于1.8之前函数并不能被当做参数传递，而且Java中变量声明可以看做是类似于ES6中的let const，自动拥有块级作用域，" /><meta name="keywords" content="Hugo, theme, even" />






<meta name="generator" content="Hugo 0.68.3 with theme even" />


<link rel="canonical" href="https://smartzheng.github.io/post/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3javascript%E4%B9%8B%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%97%AD%E5%8C%85/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">


<link href="/dist/even.c2a46f00.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="深入理解JavaScript之作用域闭包" />
<meta property="og:description" content="在Java中，由于1.8之前函数并不能被当做参数传递，而且Java中变量声明可以看做是类似于ES6中的let const，自动拥有块级作用域，" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://smartzheng.github.io/post/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3javascript%E4%B9%8B%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%97%AD%E5%8C%85/" />
<meta property="article:published_time" content="2019-08-23T00:00:00+00:00" />
<meta property="article:modified_time" content="2019-08-23T00:00:00+00:00" />
<meta itemprop="name" content="深入理解JavaScript之作用域闭包">
<meta itemprop="description" content="在Java中，由于1.8之前函数并不能被当做参数传递，而且Java中变量声明可以看做是类似于ES6中的let const，自动拥有块级作用域，">
<meta itemprop="datePublished" content="2019-08-23T00:00:00&#43;00:00" />
<meta itemprop="dateModified" content="2019-08-23T00:00:00&#43;00:00" />
<meta itemprop="wordCount" content="3122">



<meta itemprop="keywords" content="JavaScript," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="深入理解JavaScript之作用域闭包"/>
<meta name="twitter:description" content="在Java中，由于1.8之前函数并不能被当做参数传递，而且Java中变量声明可以看做是类似于ES6中的let const，自动拥有块级作用域，"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">smartzheng</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">Categories</li>
      </a>
  </ul>
</nav>
  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">smartzheng</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">Categories</a>
      </li>
  </ul>
</nav>
    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">深入理解JavaScript之作用域闭包</h1>

      <div class="post-meta">
        <span class="post-time"> 2019-08-23 </span>
        <div class="post-category">
            <a href="/categories/web%E5%89%8D%E7%AB%AF/"> web前端 </a>
            </div>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents"></nav>
  </div>
</div>
    <div class="post-content">
      <p><em><strong>在Java中，由于1.8之前函数并不能被当做参数传递，而且Java中变量声明可以看做是类似于ES6中的let const，自动拥有块级作用域，所以闭包在Java中并不是一个很需要讨论的问题，虽然Java开发（尤其是Android开发）中内存泄漏的原因和JS中因为闭包导致的内存泄漏很类似。</strong></em></p>
<p><em><strong>而JavaScript中，闭包无处不在，不过鲜有开发者能透彻地领悟它的意义。之前学习JS时，参考的是《JavaScript高级程序设计》，关于闭包，这本书讲的不可谓不深入，但总感觉理解的不是那么全面，似懂非懂，最近又仔细结合《你不知道的JavaScript》进一步加深了理解。</strong></em></p>
<p><strong>何为闭包</strong></p>
<p>先来看这个来自《JavaScript高级程序设计》中的例子：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">createComparisonFunction</span><span class="p">(</span><span class="nx">propertyName</span><span class="p">)</span> <span class="p">{</span> <span class="c1">//函数声明在全局环境中
</span><span class="c1"></span>    <span class="k">return</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">object1</span><span class="p">,</span> <span class="nx">object2</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">value1</span> <span class="o">=</span> <span class="nx">object1</span><span class="p">[</span><span class="nx">propertyName</span><span class="p">];</span>
        <span class="kd">var</span> <span class="nx">value2</span> <span class="o">=</span> <span class="nx">object2</span><span class="p">[</span><span class="nx">propertyName</span><span class="p">];</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">value1</span> <span class="o">&lt;</span> <span class="nx">value2</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">value1</span> <span class="o">&gt;</span> <span class="nx">value2</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">};</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>在上面代码中，方法createComparisonFunction返回了一个匿名方法，匿名方法中使用到了传入createComparisonFunction的参数propertyName，也就是等于说内部的匿名函数访问了外部函数中的变量。<br>
之所以能访问外部作用域中的变量，是因为该函数的作用域链中包含了外部函数的作用域，当自身作用域中找不到该变量名对应的变量时，会在其上一级作用域中查找，以此往复，这一点熟悉作用域链的人都知道，不过这里还是细讲一下：</p>
<ul>
<li>每个执行环境都会包含一个表示变量的对象，对于全局环境而言，也就是全局变量对象（window），而函数执行环境中同样也包含一个活动的变量对象（简称活动对象，之所以是活动的，是因为正常情况下它在函数执行完后会被销毁）用于表示该执行环境中的变量</li>
<li>当在全局环境中创建一个函数时，会自动创建一个作用域链，并且其中预先包含全局变量对象，这个作用域链被保存在函数的[[Scope]]属性中</li>
<li>当调用该函数时，会为函数创建一个执行环境（同时创建了函数对应的活动对象，执行环境的范围也就是函数的作用域），并且复制[[Scope]]属性中的对象，作为该执行环境的作用域链；然后将函数对应的活动对象push到作用域链的前端</li>
</ul>
<p><strong>有几个需要注意的概念：变量对象、作用域、作用域链、执行环境</strong></p>
<p>看个例子：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">compare</span><span class="p">(</span><span class="nx">value1</span><span class="p">,</span> <span class="nx">value2</span><span class="p">){</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">value1</span> <span class="o">&lt;</span> <span class="nx">value2</span><span class="p">){</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">value1</span> <span class="o">&gt;</span> <span class="nx">value2</span><span class="p">){</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
		 <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> 
	<span class="p">}</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">compare</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">);</span>
</code></pre></td></tr></table>
</div>
</div><p>根据以上规则，我们可以这么去解释上面的代码:</p>
<ul>
<li>在全局环境中有个全局变量对象window，它包含了value1、compare、result的引用；</li>
<li>在声明compare方法时，创建了一个作用域链，其中预先包含了全局变量对象，它被保存到了compare的[[Scope]]属性中</li>
<li>调用<code>compare(5, 10)</code>时，会为compare函数创建一个执行环境，并且创建一个活动对象用以保存此执行环境中的变量（即代码中的），复制compare的[[Scope]]属性对应的作用域链作为该执行环境的作用域链，并且将活动对象推入作用域链的前端</li>
<li>当函数执行时，当需要使用到某一个变量时，会在函数的作用域链中去查找该变量，首先会查找作用域链前端的活动对象中是否包含该变量的引用，如果没有在继续查找作用域链的下一层（这里即全局变量对象），以次类推</li>
</ul>
<p>正常情况下，函数执行完毕后，其执行环境的作用域会被销毁，活动对象也应该被销毁。但是在闭包中，表现却有所差异；接下来，我们在全局环境中调用createComparisonFunction函数：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"> <span class="kd">var</span> <span class="nx">compare</span> <span class="o">=</span> <span class="nx">createComparisonFunction</span><span class="p">(</span><span class="s2">&#34;name&#34;</span><span class="p">);</span>
 <span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">compare</span><span class="p">({</span> <span class="nx">name</span><span class="o">:</span> <span class="s2">&#34;Nicholas&#34;</span> <span class="p">},</span> <span class="p">{</span> <span class="nx">name</span><span class="o">:</span> <span class="s2">&#34;Greg&#34;</span> <span class="p">});</span>
</code></pre></td></tr></table>
</div>
</div><p>这里的compare被赋值为createComparisonFunction方法中的匿名函数，在执行<code>compare({ name: &quot;Nicholas&quot; }, { name: &quot;Greg&quot; })</code>时，compare函数执行在全局作用域中，但compare函数内部访问了createComparisonFunction函数作用域下的变量propertyName（即第一行传入的&quot;name&rdquo;）；同时，compare保存了createComparisonFunction函数作用域中的变量；这就出现了闭包。</p>
<p>一个完整的定义：<strong>当函数可以记住并访问所在的词法作用域，即使函数实在当前词法作用域之外执行，这时就产生了闭包</strong>（《你不知道的JavaScript上卷》）</p>
<p>在上面的例子中，在全局环境下调用compare方法，实际上是把createComparisonFunction内部的匿名函数对象的引用赋值给了window，window不会被销毁，因此它持有的compare不会被销毁，所以createComparisonFunction执行完毕后，compare中使用到的propertyName同样不会被销毁。可以手动将compare置为null来让垃圾回收器回收</p>
<p><strong>以上的解释主要来自《JavaScript高级程序设计》，直观的看，闭包似乎就是在函数中返回函数，然后在别的地方调用该函数，这个说法不可谓不对，但并不全面。下面结合《你不知道的JavaScript》来做进一步解释，可能会更理解为什么说闭包无处不在</strong><br>
其次，个人感觉《JavaScript高级程序设计》中的闭包例子有点绕，这里附一段更简单闭包代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">foo</span><span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
  <span class="kd">function</span> <span class="nx">bar</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">a</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="nx">bar</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">var</span> <span class="nx">baz</span> <span class="o">=</span> <span class="nx">foo</span><span class="p">();</span>
<span class="nx">baz</span><span class="p">();</span> <span class="c1">// 2 —— 这就是闭包的效果,foo中的a被保存了
</span></code></pre></td></tr></table>
</div>
</div><p>好了，下面再看个IIFE的例子</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
<span class="p">(</span><span class="kd">function</span> <span class="nx">IIFE</span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">a</span><span class="p">);</span>
<span class="p">})();</span>
</code></pre></td></tr></table>
</div>
</div><p>这是闭包吗？</p>
<p>从技术层面讲，它确实创建了闭包，因为<strong>函数IIFE可以记住并访问所在的词法作用域</strong>，但是IIFE并不是在自身的作用域外执行，所以，严格来讲，这并不是闭包</p>
<p>再看个更熟悉的例子：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">wait</span><span class="p">(</span><span class="nx">message</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">message</span><span class="p">);</span>
  <span class="p">},</span> <span class="mi">1000</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">wait</span><span class="p">(</span><span class="s2">&#34;Hello World&#34;</span><span class="p">);</span>
</code></pre></td></tr></table>
</div>
</div><p>在wait函数内部，将timer函数作为参数传递给setTimeout方法，timer中保存了外部作用域中的message，并且timer函数最终是被引擎调用，它执行所在的作用域并不是wait下的作用域，所以显然这里产生了闭包。</p>
<p><strong>如果将函数(函数访问了它们各自的词法作用域)当做第一级的值类型并到处传递，你就会看到闭包在这些函数中的应用。在定时器、事件监听器、Ajax 请求、跨窗口通信、Web Workers或者任何其他的异步(或者同步)任务中，只要使用了回调函数，实际上就是在使用闭包!</strong>（《你不知道的JavaScript上卷》）</p>
<p><em><strong>理解了闭包之后，接下来再看一下闭包与循环的问题</strong></em></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">i</span><span class="p">);</span>
  <span class="p">},</span> <span class="nx">i</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>类似的代码在Java或其他类C语言中，都会每隔一秒顺序打印出1到5，但在这里却输出了5个6，这也是闭包所致</p>
<p>在5次for循环中，其实依次创建了5个timer，由于闭包的存在，每个timer中都保存了所在作用域中的i变量，并且它们都是同一个变量，for循环结束后i为6，此时每个timer中保存的值也都变为了6</p>
<p>那为什么在Java中不会出现这种情况呢？原因是Java中的变量默认带有块级作用域，等于是说循环中的i与timer中的i其实是两个变量，JS中可以这样实现同样的效果：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>	
    <span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="nx">i</span><span class="p">;</span>
    <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">i</span><span class="p">);</span>
    <span class="p">},</span> <span class="nx">i</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
  <span class="p">})();</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>在for循环中通过一个IIFE创建一个新的作用域，那么该作用域中的i也就与外部作用域中的i无关了，便于理解，可以把内部的i换为j：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">i</span><span class="p">;</span>
    <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">j</span><span class="p">);</span>
    <span class="p">},</span> <span class="nx">j</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
  <span class="p">})();</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>i和j是两个无关变量，timer中保存的j只是被赋值为每一次for循环对应的i的值</p>
<p>上面的写法是对块级作用域的模仿，ES6中的let也提供块级作用域：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">let</span> <span class="nx">j</span> <span class="o">=</span> <span class="nx">i</span><span class="p">;</span> <span class="c1">// 闭包的块作用域!
</span><span class="c1"></span>  <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">j</span><span class="p">);</span>
  <span class="p">},</span> <span class="nx">j</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>或</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">for</span> <span class="p">(</span><span class="kd">let</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="nx">timer</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">j</span><span class="p">);</span>
  <span class="p">},</span> <span class="nx">j</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div>
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">smartzheng</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2019-08-23
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/javascript/">JavaScript</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3javascript%E4%B9%8B%E6%89%A7%E8%A1%8C%E7%8E%AF%E5%A2%83%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F%E9%93%BE/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">深入理解JavaScript之执行环境和作用域链</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/react-hooks%E5%AD%A6%E4%B9%A0%E4%BC%98%E5%8A%BF%E5%8F%8A%E4%BD%BF%E7%94%A8/">
            <span class="next-text nav-default">React Hooks学习：优势及使用</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:smartzheng1993@email.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/smartzheng" class="iconfont icon-github" title="github"></a>
      <a href="https://weibo.com/2062336885/profile?topnav=1&amp;wvr=6" class="iconfont icon-weibo" title="weibo"></a>
      <a href="https://www.zhihu.com/people/liu-xia-hui-89-70" class="iconfont icon-zhihu" title="zhihu"></a>
      <a href="https://www.douban.com/people/smartzheng/" class="iconfont icon-douban" title="douban"></a>
  <a href="https://smartzheng.github.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy; 
    2017 - 
    2020
    
  </span>
</div>
    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/dist/even.26188efa.min.js"></script>








</body>
</html>
